package com.macro.mall.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;

public class DataDecryptUtil {

    /**
     * 解密手机号数据
     * @param encryptedData 加密数据
     * @param sessionKey 会话密钥
     * @param iv 初始向量
     * @return 解密后的JSON字符串
     * @throws Exception 解密异常
     */
    public static String decryptPhoneNumber(String encryptedData, String sessionKey, String iv) throws Exception {
        // Base64解码
        byte[] sessionKeyBytes = Base64.decodeBase64(sessionKey);
        byte[] ivBytes = Base64.decodeBase64(iv);
        byte[] encryptedDataBytes = Base64.decodeBase64(encryptedData);

        // 创建密钥和初始向量
        SecretKeySpec keySpec = new SecretKeySpec(sessionKeyBytes, "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);

        // 初始化Cipher
        Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);

        // 解密
        byte[] decrypted = cipher.doFinal(encryptedDataBytes);

        // 去除PKCS7填充
        byte[] result = PKCS7Decoder.decode(decrypted);

        return new String(result, StandardCharsets.UTF_8);
    }

    // PKCS7解码器
    private static class PKCS7Decoder {
        public static byte[] decode(byte[] decrypted) {
            int pad = decrypted[decrypted.length - 1];
            if (pad < 1 || pad > 32) {
                pad = 0;
            }
            return Arrays.copyOfRange(decrypted, 0, decrypted.length - pad);
        }
    }
}
